package json

import (
	log "ac-common-go/glog"
	"ac-julink/rpcagent/wgctl"
	"ac-julink/tool/data"
	"encoding/json"
	"fmt"
	"strconv"
	"time"
)

// 101认证消息返回JSON
func AuthJsonCreate(_token string, _err int) (_jsonstr string, err error) {
	type authJson struct {
		MsgId int    `json:"id"`
		Token string `json:"token"`
		Err   int    `json:"err"`
	}
	var m authJson
	m.MsgId = data.DEVICE_AUTHENTICATION
	m.Token = _token
	m.Err = _err
	_jsonret, err := json.Marshal(m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_jsonstr = string(_jsonret)
	}
	return _jsonstr, err
}

type Origin102KeyJson struct {
	MsgId int    `json:"id"`
	Key   string `json:"key"`
	Err   int    `json:"err"`
}

// 102动态密钥交换消息返回JSON
func KeyJsonCreate(_key string, _err int) (_jsonstr string, err error) {
	var m Origin102KeyJson
	m.MsgId = data.EXCHANGE_ENCRYPTION_KEY
	m.Key = _key
	m.Err = _err
	_jsonret, err := json.Marshal(m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_jsonstr = string(_jsonret)
	}
	return _jsonstr, err
}

type PemFileInfo struct {
	EncryptPem string `json:"encryptPem"`
	Sign       string `json:"sign"`
}

type RootCheck102KeyJson struct {
	MsgId int    `json:"id"`
	Key   string `json:"key"`
	Err   int    `json:"err"`

	Update bool `json:"update"`
	//Version int           `json:"version"`
	//Pems    []PemFileInfo `json:"pems"`
}

func convertToPemFileInfoSlice(value interface{}) ([]PemFileInfo, error) {
	// 尝试将 interface{} 转换为 []interface{}
	pemsInterface, ok := value.([]interface{})
	if !ok {
		log.Errorf("failed to convertToPemFileInfoSlice! Expected type: []interface{}, but got: %T", value)
		return nil, fmt.Errorf("类型断言失败: 期望类型为 []interface{}，但实际类型为 %T", value)
	}

	// 将 []interface{} 转换为 []PemFileInfo
	pems := make([]PemFileInfo, len(pemsInterface))
	for i, pemInterface := range pemsInterface {
		pemMap, ok := pemInterface.(map[string]interface{})
		if !ok {
			log.Errorf("类型断言失败: 期望类型为 map[string]interface{}，但实际类型为 %T", pemInterface)
			return nil, fmt.Errorf("类型断言失败: 期望类型为 map[string]interface{}，但实际类型为 %T", pemInterface)
		}
		encryptPem, ok := pemMap["encryptPem"].(string)
		if !ok {
			log.Errorf("类型断言失败: 期望类型为 int，但实际类型为 %T", pemMap["encryptPem"])
			return nil, fmt.Errorf("类型断言失败: 期望类型为 int，但实际类型为 %T", pemMap["encryptPem"])
		}
		sign, ok := pemMap["sign"].(string)
		if !ok {
			log.Errorf("类型断言失败: 期望类型为 string，但实际类型为 %T", pemMap["sign"])
			return nil, fmt.Errorf("类型断言失败: 期望类型为 string，但实际类型为 %T", pemMap["sign"])
		}
		pems[i] = PemFileInfo{
			EncryptPem: encryptPem,
			Sign:       sign,
		}
	}
	return pems, nil
}

// 为支持根证书验证的设备返回102请求
func KeyJsonCreateRootCheck(_key string, _err int, fetchLatestCertInnerResp map[string]interface{}) (_jsonstr string, err error) {
	if fetchLatestCertInnerResp != nil && len(fetchLatestCertInnerResp) > 0 {
		var m RootCheck102KeyJson
		m.MsgId = data.EXCHANGE_ENCRYPTION_KEY
		m.Key = _key
		m.Err = _err

		if value, ok := fetchLatestCertInnerResp["needUpdate"]; ok && value != nil {
			m.Update = value.(bool)
		}

		_jsonret, err := json.Marshal(m)
		if err != nil {
			log.Errorf("%+v", err)
		} else {
			_jsonstr = string(_jsonret)
		}
		return _jsonstr, err
	} else {
		return KeyJsonCreate(_key, _err)
	}
}

// 903返回JSON
func UpdateStatusCreate(_result string, _err int) (_jsonstr string, err error) {
	type keyJson struct {
		MsgId  int    `json:"id"`
		Result string `json:"result"`
		Err    int    `json:"err"`
	}
	var m keyJson
	m.MsgId = data.REPORT_STATUS_UPDATE
	m.Result = _result
	m.Err = _err
	_jsonret, err := json.Marshal(m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_jsonstr = string(_jsonret)
	}
	return _jsonstr, err
}

// 103系统参数获取消息返回JSON
func SysParamJsonCreate(_hb, _rp, _retry string, _timezone, _err int) (_jsonstr string, err error) {
	type Args struct {
		Hb       int `json:"hb"`
		Rp       int `json:"rp"`
		Retry    int `json:"retry"`
		Time     int `json:"time"`
		Timezone int `json:"timezone"`
	}
	type SysParamJson struct {
		MsgId int    `json:"id"`
		Args  []Args `json:"args"`
		Err   int    `json:"err"`
	}

	var m SysParamJson
	m.MsgId = data.RETRIVE_SYSTEM_CONFIG
	m.Err = _err
	argstmp := make([]Args, 1)
	argstmp[0].Hb, _ = strconv.Atoi(_hb)
	argstmp[0].Rp, _ = strconv.Atoi(_rp)
	argstmp[0].Retry, _ = strconv.Atoi(_retry)
	argstmp[0].Time = int(time.Now().Unix())
	argstmp[0].Timezone = _timezone
	m.Args = argstmp
	_jsonret, err := json.Marshal(m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_jsonstr = string(_jsonret)
	}
	return _jsonstr, err
}

func SysParamJsonCreate7s(_hb, _rp, _retry string, _timezone, _err int, rkey string) (_jsonstr string, err error) {
	type Args struct {
		Hb       int    `json:"hb"`
		Rp       int    `json:"rp"`
		Retry    int    `json:"retry"`
		Time     int    `json:"time"`
		Timezone int    `json:"timezone"`
		RKey     string `json:"rkey"`
	}
	type SysParamJson struct {
		MsgId int    `json:"id"`
		Args  []Args `json:"args"`
		Err   int    `json:"err"`
	}

	var m SysParamJson
	m.MsgId = data.RETRIVE_SYSTEM_CONFIG
	m.Err = _err
	argstmp := make([]Args, 1)
	argstmp[0].Hb, _ = strconv.Atoi(_hb)
	argstmp[0].Rp, _ = strconv.Atoi(_rp)
	argstmp[0].Retry, _ = strconv.Atoi(_retry)
	argstmp[0].Time = int(time.Now().Unix())
	argstmp[0].Timezone = _timezone
	argstmp[0].RKey = rkey

	m.Args = argstmp
	_jsonret, err := json.Marshal(m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_jsonstr = string(_jsonret)
	}
	return _jsonstr, err
}

// 201控制指令下发JSON
func CmdControlJsonCreate(_cmd string, _seq, _cmdver, _type int) (_jsonstr string, err error) {
	switch _type {
	case 0: //单设备
		{
			type CmdSingleJson struct {
				MsgId      int    `json:"id"`
				Seq        int    `json:"seq"`
				Com        string `json:"com"`
				Cmdversion int    `json:"cmdversion"`
			}
			var m CmdSingleJson
			m.MsgId = data.SEND_CONTROL_COMMAND
			m.Seq = _seq
			m.Cmdversion = _cmdver
			m.Com = _cmd
			_jsonret, err := json.Marshal(m)
			if err != nil {
				log.Errorf("%+v", err)
			} else {
				_jsonstr = string(_jsonret)
			}
		}
	case 1: //一拖多设备
		{
			type MQparseMutiCmd struct {
				Cmd []struct {
					Devid string `json:"deviceid"`
					Cmd   string `json:"cmd"`
				} `json:"cmdlist"`
			}
			var p MQparseMutiCmd
			err = json.Unmarshal([]byte(_cmd), &p)
			if err != nil {
				log.Errorf("%+v", err)
			} else {
				type Mutildevcom struct {
					Devid string `json:"devid"`
					Com   string `json:"com"`
				}
				type CmdMultJson struct {
					MsgId      int           `json:"id"`
					Seq        int           `json:"seq"`
					Com        string        `json:"com"`
					Cmdversion int           `json:"cmdversion"`
					Muticom    []Mutildevcom `json:"mutidevcom"`
				}

				var cmdstr CmdMultJson
				cmdstr.MsgId = data.SEND_CONTROL_COMMAND
				cmdstr.Seq = _seq
				cmdstr.Cmdversion = _cmdver
				for _, ch := range p.Cmd {
					var muticom Mutildevcom
					muticom.Com = ch.Cmd
					muticom.Devid = ch.Devid
					cmdstr.Muticom = append(cmdstr.Muticom, muticom)
				}
				_jsonret, err := json.Marshal(cmdstr)
				if err != nil {
					log.Errorf("%+v", err)
				} else {
					_jsonstr = string(_jsonret)
				}
			}
		}
	default:
		log.Info("Default")
	}
	return _jsonstr, err
}

// 202查询指令下发JSON
func CmdQueryJsonCreate(_devid string, _seq int) (_jsonstr string, err error) {
	type cmdQueryJson struct {
		MsgId int    `json:"id"`
		Devid string `json:"devid"`
		Seq   int    `json:"seq"`
	}
	var m cmdQueryJson
	m.MsgId = data.SEND_QUERY_COMMAND
	m.Devid = _devid
	m.Seq = _seq
	_jsonret, err := json.Marshal(m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_jsonstr = string(_jsonret)
	}
	return _jsonstr, err
}

// 203重置指令下发JSON
func CmdResetJsonCreate(_seq int) (_jsonstr string, err error) {
	type cmdResetJson struct {
		MsgId int `json:"id"`
		Seq   int `json:"seq"`
	}
	var m cmdResetJson
	m.MsgId = data.SEND_CONTROL_RERET
	m.Seq = _seq
	_jsonret, err := json.Marshal(m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_jsonstr = string(_jsonret)
	}
	return _jsonstr, err
}

// 301版本号查询指令下发JSON
func VersionQueryJsonCreate(_type int) (_jsonstr string, err error) {
	type verQueryJson struct {
		MsgId int `json:"id"`
		Type  int `json:"type"`
	}
	var m verQueryJson
	m.MsgId = data.QUERY_VERSON_COMMAND
	m.Type = _type

	_jsonret, err := json.Marshal(m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_jsonstr = string(_jsonret)
	}
	return _jsonstr, err
}

// 302升级策略下发JSON
func OtaJsonCreate(_type, _len int, _ver, _md5, _addr string, _updateflag, _policyId int, _versiondesc, _signature string, _targetedType int) (_jsonstr string, err error) {
	type otaJson struct {
		MsgId        int    `json:"id"`
		Type         int    `json:"type"`
		Ver          string `json:"ver"`
		Len          int    `json:"len"`
		Md5          string `json:"md5"`
		Addr         string `json:"addr"`
		Updateflag   int    `json:"update_flag"`
		VersionDesc  string `json:"version_desc"`
		PolicyId     int    `json:"policyId"`
		Signature    string `json:"signature"`
		TargetedType int    `json:"targetedType"`
	}
	var m otaJson
	m.MsgId = data.SEND_OTA_COMMAND
	m.Type = _type
	m.Ver = _ver
	m.Len = _len
	m.Md5 = _md5
	m.Addr = _addr
	m.Updateflag = _updateflag
	m.VersionDesc = _versiondesc
	m.PolicyId = _policyId
	m.Signature = _signature
	m.TargetedType = _targetedType

	_jsonret, err := json.Marshal(m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_jsonstr = string(_jsonret)
	}
	return _jsonstr, err
}

// 303升级策略查询结果下发JSON
func OtaQueryJsonCreate(_type, _len, _updateflag, _err, _policyId int, _wifiid, _ver, _md5, _url, _versionDesc string, _targetedType int) (_jsonstr string, err error) {
	type otaQueryJson struct {
		MsgId        int    `json:"id"`
		Type         int    `json:"type"`
		Wifiid       string `json:"wifiid"`
		Ver          string `json:"wifiver"`
		Len          int    `json:"file_size"`
		Md5          string `json:"md5"`
		Url          string `json:"url"`
		Updateflag   int    `json:"update_flag"`
		Err          int    `json:"err"`
		VersionDesc  string `json:"version_desc"`
		PolicyId     int    `json:"policyId"`
		TargetedType int    `json:"targetedType"`
	}
	var m otaQueryJson
	m.MsgId = data.QUERY_OTA_COMMAND
	m.Type = _type
	m.Ver = _ver
	m.Len = _len
	m.Md5 = _md5
	m.Url = _url
	m.Wifiid = _wifiid
	m.Err = _err
	m.Updateflag = _updateflag
	m.VersionDesc = _versionDesc
	m.PolicyId = _policyId
	m.TargetedType = _targetedType

	_jsonret, err := json.Marshal(m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_jsonstr = string(_jsonret)
	}
	return _jsonstr, err
}

// 305升级策略下发JSON
func McuJsonCreate(_type, _ver, _md5, _addr, _checksum string, _len, _effectiveStart, _effectiveLen int) (_jsonstr string, err error) {
	type mcuJson struct {
		MsgId          int    `json:"id"`
		Type           string `json:"type"`
		Ver            string `json:"ver"`
		Len            int    `json:"len"`
		Md5            string `json:"md5"`
		Checksum       string `json:"checksum"`
		EffectiveStart int    `json:"effectiveStart"`
		EffectiveLen   int    `json:"effectiveLen"`
		Addr           string `json:"addr"`
	}
	var m mcuJson
	m.MsgId = data.SEND_MCU_UPGRADE_COMMAND
	m.Type = _type
	m.Ver = _ver
	m.Len = _len
	m.Md5 = _md5
	m.Checksum = _checksum
	m.EffectiveStart = _effectiveStart
	m.EffectiveLen = _effectiveLen
	m.Addr = _addr

	_jsonret, err := json.Marshal(m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_jsonstr = string(_jsonret)
	}
	return _jsonstr, err
}

// 401设备绑定结果返回JSON
func DevBindJsonCreate(_err int, _devid, _result string) (_jsonstr string, err error) {
	type devBindJson struct {
		MsgId  int    `json:"id"`
		Devid  string `json:"devid"`
		Err    int    `json:"err"`
		Result string `json:"result"`
	}
	var m devBindJson
	m.MsgId = data.BIND_DEV_COMMAND
	m.Devid = _devid
	m.Err = _err
	m.Result = _result

	_jsonret, err := json.Marshal(m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_jsonstr = string(_jsonret)
	}
	return _jsonstr, err
}

// 402设备解绑结果返回JSON
func DevUnBindJsonCreate(_err int, _devid, _result string) (_jsonstr string, err error) {
	type devUnBindJson struct {
		MsgId  int    `json:"id"`
		Devid  string `json:"devid"`
		Err    int    `json:"err"`
		Result string `json:"result"`
	}
	var m devUnBindJson
	m.MsgId = data.UNBIND_DEV_COMMAND
	m.Devid = _devid
	m.Err = _err
	m.Result = _result

	_jsonret, err := json.Marshal(m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_jsonstr = string(_jsonret)
	}
	return _jsonstr, err
}

// 403绑定设备列表结果返回JSON
func BindListJsonCreate(_err int, _devlist []string) (_jsonstr string, err error) {
	type devList struct {
		Devid string `json:"devid"`
	}
	type bindListJson struct {
		MsgId  int       `json:"id"`
		Err    int       `json:"err"`
		Count  int       `json:"count"`
		Devids []devList `json:"devids"`
	}

	var bindstr bindListJson
	for _, ch := range _devlist {
		var devid devList
		devid.Devid = ch
		bindstr.Devids = append(bindstr.Devids, devid)
	}

	bindstr.MsgId = data.GET_BIND_DEV_COMMAND
	bindstr.Err = _err
	bindstr.Count = len(_devlist)

	_jsonret, err := json.Marshal(bindstr)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_jsonstr = string(_jsonret)
	}
	return _jsonstr, err
}

// 404网关所属家庭设备列表返回JSON
func HomeBindListJsonCreate(_err int, _devlist []data.HomeDevice) (_jsonstr string, err error) {
	type devList struct {
		Wifiid      string `json:"wifiid"`
		Deviceid    string `json:"deviceid"`
		DevTypeCode string `json:"devTypeCode"`
	}
	type homeDevListJson struct {
		MsgId   int       `json:"id"`
		Err     int       `json:"err"`
		Count   int       `json:"count"`
		Devlist []devList `json:"deviceList"`
	}

	var homedevstr homeDevListJson
	for _, ch := range _devlist {
		var devinfo devList
		devinfo.Wifiid = ch.GetWifiId()
		devinfo.Deviceid = ch.GetDeviceId()
		devinfo.DevTypeCode = ch.GetDeviceTypeCode()
		homedevstr.Devlist = append(homedevstr.Devlist, devinfo)
	}

	homedevstr.MsgId = data.GET_HOME_DEVLIST_COMMAND
	homedevstr.Err = _err
	homedevstr.Count = len(_devlist)

	_jsonret, err := json.Marshal(homedevstr)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_jsonstr = string(_jsonret)
	}
	return _jsonstr, err
}

// 406设备扩展信息存储返回JSON
func DevExtInfoJsonCreate(_err int, _devid, _extInfo string) (_jsonstr string, err error) {
	type devExtInfoJson struct {
		MsgId   int    `json:"id"`
		Err     int    `json:"err"`
		DevId   string `json:"devId"`
		ExtInfo string `json:"extInfo"`
	}
	var m devExtInfoJson
	m.MsgId = data.DEVICE_EXTINFO_STORE
	m.Err = _err
	m.DevId = _devid
	m.ExtInfo = _extInfo

	_jsonret, err := json.Marshal(m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_jsonstr = string(_jsonret)
	}
	return _jsonstr, err
}

// 407设备重置结果返回JSON
func DevResetJsonCreate(_err, _oprtype int, _wifiid string) (_jsonstr string, err error) {
	type devResetJson struct {
		MsgId   int    `json:"id"`
		Err     int    `json:"err"`
		WifiId  string `json:"wifiId"`
		OprType int    `json:"oprType"`
	}
	var m devResetJson
	m.MsgId = data.DEVICE_RESET
	m.Err = _err
	m.WifiId = _wifiid
	m.OprType = _oprtype
	_jsonret, err := json.Marshal(m)
	if err != nil {
		log.Errorf("DevResetJsonCreate:%+v", err)
	} else {
		_jsonstr = string(_jsonret)
	}
	return _jsonstr, err
}

// 501网关所在家庭的场景信息返回JSON
func HomeSceneInfoJsonCreate(_err int, _result string, _sceneinfo []data.SceneIdInfo) (_jsonstr string, err error) {
	type sceneInfo struct {
		SceneId    string `json:"sceneid"`
		SceneType  int    `json:"scenetype"`
		Updatetime string `json:"updatetime"`
	}
	type homeSceneInfoJson struct {
		MsgId       int         `json:"id"`
		Err         int         `json:"err"`
		Result      string      `json:"result"`
		SceneidList []sceneInfo `json:"sceneidlist"`
	}
	var hsInfo homeSceneInfoJson
	for _, ch := range _sceneinfo {
		var sceneinfo sceneInfo
		sceneinfo.SceneId = strconv.Itoa(ch.GetSceneId())
		sceneinfo.SceneType = ch.GetSceneType()
		sceneinfo.Updatetime = strconv.Itoa(ch.GetUpdateTime())
		hsInfo.SceneidList = append(hsInfo.SceneidList, sceneinfo)
	}
	hsInfo.MsgId = data.GET_SCENE_LIST_COMMAND
	hsInfo.Err = _err
	hsInfo.Result = _result

	_jsonret, err := json.Marshal(hsInfo)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_jsonstr = string(_jsonret)
	}
	return _jsonstr, err
}

// 502场景信息查询返回JSON
func SceneInfoQueryJsonCreate(_err int, _result string, _sceneinfo []data.Scene) (_jsonstr string, err error) {
	type Cmd struct {
		//指令信息
		CmdOrder  int    `json:"cmdorder"`
		CmdId     int    `json:"cmdid"`
		CmdParam  int    `json:"cmdparam"`
		DeviceId  string `json:"deviceid"`
		WifiId    string `json:"wifiid"`
		DelayTime int    `json:"delaytime"`
	}
	type SceneCondition struct {
		//场景条件信息
		SceneConditionId string `json:"sceneconditionid"`
		DeviceId         string `json:"deviceid"`
		WifiId           string `json:"wifiid"`
		StatusValue      int    `json:"statusvalue"`
		OperateType      int    `json:"operatetype"`
		StatusParamValue int    `json:"statusparamvalue"`
	}
	type SceneValidTime struct {
		//场景有效时间信息
		StartTime string `json:"startTime"`
		EndTime   string `json:"endTime"`
	}
	type Scene struct {
		//场景信息
		SceneId            string           `json:"sceneid"`
		HomeId             string           `json:"homeid"`
		SceneName          string           `json:"scenename"`
		SceneType          int              `json:"scenetype"`
		Status             int              `json:"status"`
		Cmdlist            []Cmd            `json:"cmdlist"`
		SceneConditionList []SceneCondition `json:"sceneconditionlist"`
		Updatetime         string           `json:"updatetime"`
		ConSceneid         string           `json:"consceneid"`
		Conrelation        int              `json:"conrelation"`
		ValidTimeList      []SceneValidTime `json:"validTimeList"`
	}
	type SceneQueryJson struct {
		MsgId     int     `json:"id"`
		Err       int     `json:"err"`
		Result    string  `json:"result"`
		SceneList []Scene `json:"scenelist"`
	}
	var scenequery SceneQueryJson
	for i, ch := range _sceneinfo {
		var sceneInfo Scene
		sceneInfo.SceneId = strconv.Itoa(ch.GetSceneId())
		sceneInfo.HomeId = strconv.Itoa(ch.GetHomeId())
		sceneInfo.SceneName = ch.GetSceneName()
		sceneInfo.SceneType = ch.GetSceneType()
		sceneInfo.Status = ch.GetStatus()
		sceneInfo.Updatetime = strconv.Itoa(ch.GetUpdatetime())
		sceneInfo.ConSceneid = strconv.Itoa(ch.GetConSceneId())
		sceneInfo.Conrelation = ch.GetConrelation()

		log.Infof("SceneId:%s", sceneInfo.SceneId, " HomeId:%s", sceneInfo.HomeId, " SceneName:%s", sceneInfo.SceneName, " SceneType:%d", sceneInfo.SceneType)
		for _, chcmd := range _sceneinfo[i].GetCmdList() {
			var cmd Cmd
			cmd.CmdId = chcmd.GetCmdId()
			cmd.CmdOrder = chcmd.GetCmdOrder()
			cmd.CmdParam = chcmd.GetCmdParam()
			cmd.DeviceId = chcmd.GetDeviceId()
			cmd.WifiId = chcmd.GetWifiId()
			cmd.DelayTime = chcmd.GetDelayTime()
			log.Infof("CmdId:%d", cmd.CmdId, " CmdOrder:%d", cmd.CmdOrder, " CmdParam:%d", cmd.CmdParam, " DeviceId:%s", cmd.DeviceId, " WifiId:%s", cmd.WifiId)
			sceneInfo.Cmdlist = append(sceneInfo.Cmdlist, cmd)
		}
		for _, chcon := range _sceneinfo[i].GetSceneConditionList() {
			var scenecon SceneCondition
			scenecon.SceneConditionId = strconv.Itoa(chcon.GetSceneConditionId())
			scenecon.DeviceId = chcon.GetDeviceId()
			scenecon.WifiId = chcon.GetWifiId()
			scenecon.StatusValue = chcon.GetStatusValue()
			scenecon.OperateType = chcon.GetOperateType()
			scenecon.StatusParamValue = chcon.GetStatusParamValue()
			sceneInfo.SceneConditionList = append(sceneInfo.SceneConditionList, scenecon)
		}
		for _, chtime := range _sceneinfo[i].GetValidTimeList() {
			var valtime SceneValidTime
			valtime.StartTime = chtime.GetStartTime()
			valtime.EndTime = chtime.GetEndTime()
			sceneInfo.ValidTimeList = append(sceneInfo.ValidTimeList, valtime)
		}
		scenequery.SceneList = append(scenequery.SceneList, sceneInfo)
	}
	scenequery.MsgId = data.GET_SCENE_INFO_COMMAND
	scenequery.Err = _err
	scenequery.Result = _result

	_jsonret, err := json.Marshal(scenequery)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_jsonstr = string(_jsonret)
	}
	return _jsonstr, err
}

// 503场景变更消息下发JSON
func SceneChangeJsonCreate(_sceneid string, _optype int) (_jsonstr string, err error) {
	type SceneChangJson struct {
		MsgId   int    `json:"id"`
		Sceneid string `json:"sceneid"`
		Optype  int    `json:"optype"`
	}
	var m SceneChangJson
	m.MsgId = data.SEND_SCENE_MODIFY_COMMAND
	m.Sceneid = _sceneid
	m.Optype = _optype
	_jsonret, err := json.Marshal(m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_jsonstr = string(_jsonret)
	}
	return _jsonstr, err
}

// 504场景执行消息下发JSON
func SceneExecuteJsonCreate(_sceneid, _wifiid, _devid, _devtype string, _optype, _exetype int) (_jsonstr string, err error) {
	type ConDevInfo struct {
		WifiId  string `json:"wifiId"`
		Devid   string `json:"deviceId"`
		Devtype string `json:"deviceType"`
	}
	type SceneExecuteJson struct {
		MsgId   int          `json:"id"`
		Sceneid string       `json:"sceneid"`
		Exetype int          `json:"exeType"`
		ConDev  []ConDevInfo `json:"conditionDeviceInfo"`
	}
	var m SceneExecuteJson
	m.MsgId = data.SEND_SCENE_EXE_COMMAND
	m.Sceneid = _sceneid
	m.Exetype = _exetype

	var condev ConDevInfo
	condev.Devid = _devid
	condev.Devtype = _devtype
	condev.WifiId = _wifiid

	m.ConDev = append(m.ConDev, condev)

	_jsonret, err := json.Marshal(m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_jsonstr = string(_jsonret)
	}
	return _jsonstr, err
}

// 601配置数据指令下发JSON
func CmdConfigDataJsonCreate(_devid string, _seq int, _dataType, _data string) (_jsonstr string, err error) {
	type cmdConfigDataJson struct {
		MsgId    int    `json:"id"`
		DevId    string `json:"devid"`
		Seq      int    `json:"seq"`
		DataType string `json:"dataType"`
		Data     string `json:"data"`
	}
	var m cmdConfigDataJson
	m.MsgId = data.SEND_CONFIG_DATA_COMMAND
	m.DevId = _devid
	m.Seq = _seq
	m.DataType = _dataType
	m.Data = _data
	_jsonret, err := json.Marshal(m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_jsonstr = string(_jsonret)
	}
	return _jsonstr, err
}

// 602配置数据上报结果JSON
func ReportConfigDataJsonResult(_devid string, _seq int, _dataType, _data string, _err int) (_jsonstr string, err error) {
	type cmdConfigDataJson struct {
		MsgId    int    `json:"id"`
		DevId    string `json:"devid"`
		Seq      int    `json:"seq"`
		DataType string `json:"dataType"`
		Data     string `json:"data"`
		Err      int    `json:"err"`
	}
	var m cmdConfigDataJson
	m.MsgId = data.REPORT_CONFIG_DATA
	m.DevId = _devid
	m.Seq = _seq
	m.DataType = _dataType
	m.Data = _data
	m.Err = _err
	_jsonret, err := json.Marshal(m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		_jsonstr = string(_jsonret)
	}
	return _jsonstr, err
}

// 902心跳消息返回JSON
func HeartBeatJsonCreate() (_jsonstr string, err error) {
	type HeartBeatJson struct {
		MsgId int `json:"id"`
	}
	var m HeartBeatJson
	m.MsgId = data.REPORT_HEARTBEAT_COMMAND

	_jsonret, err := json.Marshal(m)
	if err != nil {
		log.Errorf("%+v", err)
		return "", err
	} else {
		_jsonstr = string(_jsonret)
	}
	//7.pacakage msg,组装HS{}MD5\r\n格式数据包
	msgHead := "HS"
	msgPack := msgHead + _jsonstr
	msgPack = msgPack + "\r\n"
	return msgPack, err
}

// RabbbitMQ消息JSON
func RabbitMqJsonCreate(_wifiid, status string, devtype, seq, cmdver, statusver int, _devstatuslist []data.DeviceData) (_jsonstr string, err error) {
	//RabbitMq消息格式
	type ParseStatus struct {
		//一对一设备解析的数据格式
		Status []struct {
			Msgtype    int    `json:"msgtype"`
			Msgsubtype int    `json:"msgsubtype"`
			Result     string `json:"result"`
		} `json:"status"`
	}
	type ParseMultStatus struct {
		//一拖多设备解析的数据格式
		Status []struct {
			Devid  string `json:"devid"`
			Status []struct {
				Msgtype    int    `json:"msgtype"`
				Msgsubtype int    `json:"mstsubtype"`
				Result     string `json:"result"`
			} `json:"status"`
		} `json:"status"`
	}
	//RabbitMQ组装的JSON数据结构
	type Status struct {
		Msgtype    int    `json:"msgtype"`
		Msgsubtype int    `json:"msgsubtype"`
		Result     string `json:"result"`
	}
	type SingleMqStr struct {
		//一对一
		Wifiid        string   `json:"wifiid"`
		Deviceid      string   `json:"deviceid"`
		DevType       int      `json:"type"`
		Status        []Status `json:"status"`
		Cmdseq        int      `json:"cmdseq"`
		Cmdversion    int      `json:"cmdversion"`
		Statusversion int      `json:"statusversion"`
	}
	type MultStatus struct {
		//一拖多设备数据格式
		Devid  string   `json:"devid"`
		Status []Status `json:"status"`
	}
	type MultMqStr struct {
		//一拖多
		Wifiid        string       `json:"wifiid"`
		DevType       int          `json:"type"`
		Status        []MultStatus `json:"status"`
		Cmdseq        int          `json:"cmdseq"`
		Cmdversion    int          `json:"cmdversion"`
		Statusversion int          `json:"statusversion"`
	}
	//1.根据一对一设备还是一拖多设备分别处理
	if devtype == data.MULTDEVICETYPE { //2.0一拖多设备,调用新接口
		var mqstr MultMqStr
		mqstr.Wifiid = _wifiid
		mqstr.Cmdseq = seq
		mqstr.Statusversion = statusver
		mqstr.Cmdversion = cmdver
		mqstr.DevType = 2

		mstatus := make([]MultStatus, len(_devstatuslist))
		for j, ch := range _devstatuslist {

			mstatus[j].Devid = ch.GetDeviceId()
			//解析status
			var m ParseStatus
			err = json.Unmarshal([]byte(ch.GetValue()), &m)
			if err != nil {
				log.Error(err)
			} else {
				statustmp := make([]Status, len(m.Status))
				for i, ch := range m.Status {
					statustmp[i].Msgtype = ch.Msgtype
					statustmp[i].Msgsubtype = ch.Msgsubtype
					statustmp[i].Result = ch.Result
					mstatus[j].Status = append(mstatus[j].Status, statustmp[i])
				}
				mqstr.Status = mstatus
			}
		}
		_jsonret, err := json.Marshal(mqstr)
		if err != nil {
			log.Errorf("error:", err)
		} else {
			_jsonstr = string(_jsonret)
		}

	} else { //一对一设备
		var m ParseStatus
		err = json.Unmarshal([]byte(status), &m)
		if err != nil {
			log.Error(err)
		} else {
			var mqstr SingleMqStr
			mqstr.Wifiid = _wifiid
			mqstr.Cmdseq = seq
			mqstr.Statusversion = statusver
			mqstr.Cmdversion = cmdver
			mqstr.Deviceid = ""
			mqstr.DevType = 1
			statustmp := make([]Status, len(m.Status))
			for i, ch := range m.Status {
				statustmp[i].Msgtype = ch.Msgtype
				statustmp[i].Msgsubtype = ch.Msgsubtype
				statustmp[i].Result = ch.Result
				mqstr.Status = append(mqstr.Status, statustmp[i])
			}
			_jsonret, err := json.Marshal(mqstr)
			if err != nil {
				log.Errorf("error:", err)
			} else {
				_jsonstr = string(_jsonret)
			}
		}
	}
	return _jsonstr, err
}

// kafka 控制状态的JSON
type ReportDeviceCmdResultReq struct {
	WifiId              string                  `json:"wifiid"`
	CmdSeq              int32                   `json:"cmdseq"`
	DeviceCmdResultList []*wgctl.CmdExecResult_ `json:"devicecmdresultlist"`
	Status              string                  `json:"status"`
	CmdVersion          int32                   `json:"cmdversion"`
	StatusVersion       int32                   `json:"statusversion"`
}

func KafkaJsonCreateCmdResult(wifiid string, cmdno int32, resultlist []*wgctl.CmdExecResult_, status string, cmdversion int32, statusversion int32) (_jsonstr string, err error) {
	log.Infof("KafkaJsonCreateCmdResult ==>>%s", wifiid)
	req := ReportDeviceCmdResultReq{
		WifiId:              wifiid,
		CmdSeq:              cmdno,
		DeviceCmdResultList: resultlist,
		Status:              status,
		CmdVersion:          cmdversion,
		StatusVersion:       statusversion,
	}
	payload, err := json.Marshal(req)
	if err != nil {
		log.Errorf("josn marshal: req[%+v], err[%v]", req, err)
		return "", err
	}
	return string(payload), nil
}

//Kafka 901 状态消息的JSON

type ReportDeviceStatusReq struct {
	WifiId           string              `json:"wifiid"`
	DeviceStatusList []*wgctl.DeviceData `json:"devicestatuslist"`
	CmdSeq           int64               `json:"cmdseq"`
	CmdVersion       int32               `json:"cmdversion"`
	StatusVersion    int32               `json:"statusversion"`
}

func KafkaJsonCreateStatus(wifiid string, cmdseq int64, statuslist []*wgctl.DeviceData, cmdversion int32, statusversion int32) (_jsonstr string, err error) {
	log.Infof("KafkaMqJsonCreate ==>>%s", wifiid)
	req := ReportDeviceStatusReq{
		WifiId:           wifiid,
		DeviceStatusList: statuslist,
		CmdSeq:           cmdseq,
		CmdVersion:       cmdversion,
		StatusVersion:    statusversion,
	}

	payload, err := json.Marshal(req)
	if err != nil {
		log.Errorf("josn marshal: req[%+v], err[%v]", req, err)
		return "", err
	}

	return string(payload), err
}
